package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Stack;

/**
 *
 *
 * @date 2024-06-29 03:21:25
 * @author zhangxiaofanfan
 */
public class HotCode070 {
    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-3);
        System.out.println(minStack.getMin());
        minStack.pop();
        System.out.println(minStack.top());
        System.out.println(minStack.getMin());
    }

}

class MinStack {

    private Stack<Integer> stack = new Stack<>();
    private PriorityQueue<Integer> pq = new PriorityQueue<>();
    private Map<Integer, Integer> map = new HashMap<>();

    public MinStack() {
    }

    public void push(int val) {
        stack.push(val);
        map.put(val, map.getOrDefault(val, 0) + 1);
        pq.add(val);
    }

    public void pop() {
        Integer pop = stack.pop();
        map.put(pop, map.get(pop) - 1);
        if (map.get(pop) <= 0) {
            map.remove(pop);
        }
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        while (map.getOrDefault(pq.peek(), 0) <= 0) {
            pq.poll();
        }
        return pq.peek();
    }
}

